import { createSlice, configureStore, createAsyncThunk } from '@reduxjs/toolkit'

const initialcountState = {
  count: 0,
  msg: '轩轩',
  loading: false,
  color: "blue",
}

export const asyncMsg = createAsyncThunk('yyy', () => {
  return new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      resolve('轩轩喜欢出去玩')
    }, 1000)
  })
})

//创建count相关的slice对象
export const countSlice = createSlice({
  name: 'count',
  initialState: initialcountState,
  reducers: {
    add: (state, action) => {
      state.count = state.count + action.payload
    },
    sub: (state: any, action: any) => {
      state.count = state.count - action.payload
    },
  },
  extraReducers(builder) {
    builder.addCase(asyncMsg.pending, (state, action) => {
      state.loading = true
      console.log('正在异步操作')
    })
    builder.addCase(asyncMsg.fulfilled, (state, action) => {
      state.loading = false
      state.msg = action.payload
      state.color = "red"
      console.log('异步操作成功')
    })
    builder.addCase(asyncMsg.rejected, (state, action) => {
      state.loading = false
      console.log('异步操作失败')
    })
  },
})

const initiallistState = {
  arr:["a","b","c"]
}

// 创建list相关的slice对象
export const listSlice = createSlice({
  name: "list",
  initialState: initiallistState,
  reducers:{
    push:(state,action)=>{
      state.arr.push(action.payload)
    }
  }
})

//创建store
const store = configureStore({
  reducer: {
    count: countSlice.reducer,
    list: listSlice.reducer,
  },
})

store.subscribe(() => {
  console.log(store.getState())
})

// store.dispatch({ type: 'count/add', payload: 1 }) //这个方式用的少

//如果使用slice对象的actions属性，action的属性使用payload
// store.dispatch(testSlice.actions.add(3))
// console.log(testSlice.actions.add(undefined));

export type RootState = ReturnType<typeof store.getState> //解决获取状态时,ts编译错误
export type AppDispatch = typeof store.dispatch // 解决异步操作时dispatch位置的ts编译错误

export default store
